package com.oa.android;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.oa.android.activity.WelcomeActivity;
import com.oa.android.entry.OALocal;
import com.oa.android.fragment.MyFragment;
import com.oa.android.fragment.TxlFragment;
import com.oa.android.fragment.WorkFragment;
import com.oa.android.server.LocateService;
import com.oa.android.server.OnePixelReceiver;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;
import com.watermeter.android.utils.DownLoadApp;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class MainActivity extends FragmentActivity implements View.OnClickListener {


    private RadioGroup group;
    private RadioButton homeRB;
    private RadioButton advtereRB;
    private RadioButton myRB;
    private FrameLayout layout;
    static final int NUM_ITEMS = 3;//一共四个fragment
    public static boolean isForeground;
    public static MainActivity mainActivity;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    private MessageReceiver mMessageReceiver;
    private static final String TAG = "MainActivity";
    private String pahth ;

    /////////////////定位\\\\\\\\\\\\\\\\\\
    public String longitude;
    public String latitude;
    private LocationClientOption.LocationMode tempMode = LocationClientOption.LocationMode.Hight_Accuracy;
    private String tempcoor = "bd09ll";
    public LocationClient mLocationClient = null;
    public MyLocationListenner myListener = new MyLocationListenner();
    private OnePixelReceiver onePixelReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainActivity=this;
//        Intent intent = new Intent("com.oa.android.server.OnePixelReceiver");
//        intent.putExtra("name","AAAAAAAAAAA");
//        this.sendBroadcast(intent);
        pahth = Environment.getExternalStorageDirectory().getPath()+"/OA/";
        JPushInterface.init(getApplicationContext());
        updateVersion();
        initView();
        registerMessageReceiver();
        group.check(R.id.homeRb);
        String string=UConstants.ComId+UConstants.EmpId;
        String[] sArray = string.split(",");
        Set<String> tagSet = new LinkedHashSet<String>();
        for (String sTagItme : sArray) {
            if (!isValidTagAndAlias(sTagItme)) {

                return;
            }
            tagSet.add(sTagItme);
        }

        //调用JPush API设置Tag
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, tagSet));

        mLocationClient = new LocationClient(this);
        mLocationClient.registerLocationListener(myListener);
        setLocationOption();
//        mLocationClient.start();
       //注册监听屏幕的广播
        onePixelReceiver = new OnePixelReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.SCREEN_OFF");
        intentFilter.addAction("android.intent.action.SCREEN_ON");
        intentFilter.addAction("android.intent.action.USER_PRESENT");
        registerReceiver(onePixelReceiver, intentFilter);


//        mLocationClient.start();// 启动定位
        Intent startIntent = new Intent(this, LocateService.class);
        startService(startIntent);
    }

    @Override
    protected void onStart() {
        super.onStart();


    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        System.out.println("AAAAAAAAAAAAAA");
        if(null!=mLocationClient){
            mLocationClient.stop();
        }
        Intent startIntent = new Intent(this, LocateService.class);
        startService(startIntent);
    }

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
        if (null==com.oa.android.utils.UConstants.EmpId){
            startActivity(new Intent(this, WelcomeActivity.class));
            finish();
        }

    }

    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        System.out.println("BBBBBBBBBBBBBB");
        unregisterReceiver(mMessageReceiver);
        if (mLocationClient != null && mLocationClient.isStarted()) {
            mLocationClient.stop();
        }
        mainActivity = this;
        super.onDestroy();
    }
    // 校验Tag Alias 只能是数字,英文字母和中文
    public  boolean isValidTagAndAlias(String s) {
        Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_!@#$&*+=.|]+$");
        Matcher m = p.matcher(s);
        return m.matches();
    }


    private void initView() {
        layout = (FrameLayout) findViewById(R.id.layout);
        group = (RadioGroup) findViewById(R.id.mHomeRadioGroup);
        homeRB = (RadioButton) findViewById(R.id.homeRb);
        advtereRB = (RadioButton) findViewById(R.id.advterRb);
        myRB = (RadioButton) findViewById(R.id.myRb);
        //监听事件：为底部的RadioGroup绑定状态改变的监听事件
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int index = 0;
                switch (checkedId) {
                    case R.id.homeRb:
                        index = 0;
                        break;
                    case R.id.advterRb:
                        index = 1;
                        break;
                    case R.id.myRb:
                        index = 2;
                        break;

                }

                //通过fragments这个adapter还有index来替换帧布局中的内容
                Fragment fragment = (Fragment) fragments.instantiateItem(layout, index);
                //一开始将帧布局中 的内容设置为第一个
                fragments.setPrimaryItem(layout, 0, fragment);
                fragments.finishUpdate(layout);

            }
        });
    }


    //用adapter来管理四个Fragment界面的变化。注意，我这里用的Fragment都是v4包里面的
    FragmentStatePagerAdapter fragments = new FragmentStatePagerAdapter(getSupportFragmentManager()) {

        @Override
        public int getCount() {
            return NUM_ITEMS;//一共有四个Fragment
        }

        //进行Fragment的初始化
        @Override
        public Fragment getItem(int i) {
            Fragment fragment = null;
            switch (i) {
                case 0://首页
                    fragment = new WorkFragment();
                    break;
                case 1://发现
                    fragment = new TxlFragment();
                    break;

                case 2://搜索
                    fragment = new MyFragment();
                    break;

                default:
                    new WorkFragment();
                    break;

            }

            return fragment;
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (keyCode == KeyEvent.KEYCODE_BACK
                    && event.getAction() == KeyEvent.ACTION_DOWN) {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast.makeText(getApplicationContext(), "再按一次退出程序",
                            Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {
                    finish();
                    System.exit(0);
                }
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
        return true;
    }


    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);

                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);

                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }


        }

    };


    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);

                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);

                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }


        }

    };
    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;

                case MSG_SET_TAGS:
                    Log.d(TAG, "Set tags in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, mTagsCallback);
                    break;

                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };



    class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                if (!TextUtils.isEmpty(extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }
                Toast.makeText(getApplicationContext(),showMsg.toString(),Toast.LENGTH_SHORT).show();

            }
        }
    }

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }


    // //////////////////////////定位\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
        // TODO Auto-generated method stub
        option.setLocationMode(tempMode);// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType(tempcoor);// 可选，默认gcj02，设置返回的定位结果坐标系，
        int span = 1000 * 30;
        System.out.println("span==="+span);
        option.setScanSpan(span);// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(false);// 可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);// 可选，默认false,设置是否使用gps
        option.setLocationNotify(false);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIgnoreKillProcess(true);// 可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        option.setIsNeedLocationDescribe(true);// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(false);// 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        mLocationClient.setLocOption(option);

    }
Util saveUtil = new Util();
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation arg0) {
            // TODO Auto-generated method stub
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            if (arg0 != null) {
                String time = dateFormat.format(new Date());

                longitude = arg0.getLongitude() + "";
                latitude = arg0.getLatitude() + "";
                // handler.sendEmptyMessage(1);
//                mLocationClient.stop();
                Log.i("longitude==", longitude);
                Log.i("time==", time);

                OALocal jWdu = new OALocal();
                jWdu.setLatitude(latitude);
                jWdu.setLongitude(longitude);

                jWdu.setTime(time);

                try {
                    MyApplication.dbManager.saveOrUpdate(jWdu);
                    List<OALocal> list = MyApplication.dbManager.selector(OALocal.class).findAll();
                    if (list != null && list.size() > 0) {
                        Log.i("list==size", list.size() + "");
                        Gson gson = new Gson();
                        String json=gson.toJson(list);//将更新数组
                        String jsb = gson.toJson(jWdu);
//                        saveUtil.writeTxtToFile(jsb,pahth,"Journal.txt");
                        Util.makeRootDirectory(pahth);
                        save(jsb);
                        String str="{\"success\":\"true\", \"rows\":"+json+"}";
                        Log.i("list==size", str);
                        try {
                        String imeiStr=getImei(MainActivity.this);
                        updateGPS(longitude+","+latitude,imeiStr);
                        } catch (Exception e) {
                           Toast.makeText(MainActivity.this,"请先设置应用的所用权限打开",Toast.LENGTH_SHORT);
                        }
                    }
                } catch (DbException e) {
                    Log.i("AAAAAAAAAAAAAA","数据库异常");
                    e.printStackTrace();
                }

            }
        }

    }

    public  String getImei(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String imei = telephonyManager.getDeviceId();
        return imei;
    }

    //上传路线
    private void updateGPS(final String mar,String imeiStr) {
//        dialog = ProgressDialog.show(this, null, "上传中...", true, false);
        com.oa.android.utils.Util.printLog("UConstants.UP_WZ---",UConstants.UP_WZ);
        RequestParams params = new RequestParams(UConstants.UP_WZ);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("EMPID",UConstants.EmpId);

        params.addBodyParameter("IMEI",imeiStr);
        params.addBodyParameter("LNG", mar);
        System.out.println("EMPID="+UConstants.EmpId+"&IMEI="+imeiStr+"&LNG="+mar+"&LKind=OA");
//
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                        if (success) {
                            try {
                                MyApplication.dbManager.delete(OALocal.class);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "地址错误或服务器无法连接！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
            }

            @Override
            public void onFinished() {

            }
        });
    }


    private Dialog dialog;

    /**
     * 更新提示
     */
    private void updateDialog(String desc, final String url, final String force) {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.exti_dialog, null);
        // 对话框
        dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCancelable(false);// 设置点击屏幕Dialog不消失
        dialog.show();

        dialog.setContentView(layout);
        final TextView sure = (TextView) layout.findViewById(R.id.sureExti);
        final TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
        TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
        dialogTitle.setText(desc);
            if (!TextUtils.isEmpty(force)&&force.equals("1")){
                sure.setText("更新");
                cancle.setText("退出应用");
            }else {
                sure.setText("更新");
                cancle.setText("取消");
            }



        sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // ContextUtil.getInstance().finishApp();

                dialog.dismiss();
                DownLoadApp downLoadApp=
                        new DownLoadApp(url,null,MainActivity.this);
                downLoadApp.showDownLoadProgress();
                downLoadApp.start();


            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.dismiss();

                if (!TextUtils.isEmpty(force)&&force.equals("1")){
                   finish();
                }

            }
        });
    }


    //上传路线
    private void updateVersion() {
//        dialog = ProgressDialog.show(this, null, "上传中...", true, false);
        RequestParams params = new RequestParams("http://www.gzskcb.com/res/oa/version.json");
//        params.addBodyParameter("LKind", "OA");
//        params.addBodyParameter("EMPID",UConstants.EmpId);
//
//        params.addBodyParameter("IMEI",imeiStr);
//        params.addBodyParameter("LNG", mar);
//
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        String  version = object.getString("version");
                        if (null!=version){
                            if (!version.equals(com.oa.android.utils.Util.getVersionName(MainActivity.this))){
                                updateDialog(object.getString("description"),object.getString("url"),object.getString("force"));
                            }
                        }
//
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "地址错误或服务器无法连接！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
            }

            @Override
            public void onFinished() {

            }
        });
    }


    /**
     * 定义文件保存的方法，写入到文件中，所以是输出流
     */
    public void save(String content) {
//        String content = "广告位编号：" + adNum + "，播放时长：" + time;
        FileOutputStream fos = null;
        try {
            // Context.MODE_PRIVATE私有权限，Context.MODE_APPEND追加写入到已有内容的后面
            fos = openFileOutput(pahth+"Journal.txt", Context.MODE_APPEND);
            fos.write(content.getBytes());
            fos.write("\r\n".getBytes());//写入换行
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



}